package com.mf.morefun.ui.moreread;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.DataSource;
import com.bumptech.glide.load.engine.GlideException;
import com.bumptech.glide.load.resource.bitmap.CircleCrop;
import com.bumptech.glide.load.resource.bitmap.RoundedCorners;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.target.Target;
import com.mf.morefun.MoreFunApplication;
import com.mf.morefun.R;
import com.mf.morefun.adapter.TestRankAdapter;
import com.mf.morefun.base.BaseBusActivity;
import com.mf.morefun.bean.ResultBean;
import com.mf.morefun.bean.TestBean;
import com.mf.morefun.bean.TestRankBean;
import com.mf.morefun.constant.Configuration;
import com.mf.morefun.listener.MyRequestListener;
import com.mf.morefun.requestbean.RequestTestBean;
import com.mf.morefun.requestbean.RequestTestRankBean;
import com.mf.morefun.ui.userinfo.LoginActivity;
import com.mf.morefun.util.GetUserInfo;
import com.mf.morefun.util.IsLoginBean;
import com.mf.morefun.util.TransformationUtils;
import com.mf.morefun.widget.NetErrorPop;
import com.mf.morefun.widget.RoundProcessDialog;
import com.mf.morefun.widget.TransformationTestUtils;
import com.zhcx.zhcxlibrary.utils.AppManager;
import com.zhcx.zhcxlibrary.utils.DeviceUtils;
import com.zhcx.zhcxlibrary.utils.SPUtils;
import com.zhcx.zhcxlibrary.utils.StringUtils;
import com.zhcx.zhcxlibrary.utils.ToastUtils;

import org.jetbrains.annotations.Nullable;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.image.ImageOptions;
import org.xutils.x;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static android.support.constraint.Constraints.TAG;

/*
测试
 */
public class TestActivity extends BaseBusActivity {
    @BindView(R.id.iv_back)
    ImageView ivBack;
    @BindView(R.id.iv_head)
    ImageView ivHead;
    @BindView(R.id.tv_name)
    TextView tvName;
    @BindView(R.id.tv_recharge)
    TextView tvRecharge;
    @BindView(R.id.lv_rank)
    ListView lvRank;
    private RoundProcessDialog dialog;
    private List<TestRankBean> testRankList = new ArrayList<>();
    private String testId = "";
    private TestRankAdapter adapter;
    private SPUtils mSputils;

    @Override
    protected int getNaviteColor() {
        return 0;
    }

    @Override
    protected int getContentLayoutId() {
        return R.layout.activity_test;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        mSputils = new SPUtils(TestActivity.this);
        if (!IsLoginBean.isNo(false)) {
            GetUserInfo.initLogin(mSputils.getString(Configuration.USERPHONE), mSputils.getString(Configuration.USERPASSWORD));
        }
        dialog = new RoundProcessDialog(TestActivity.this, "");
        adapter = new TestRankAdapter(TestActivity.this, testRankList);
        lvRank.setAdapter(adapter);
        //先查询测试id
        if (!StringUtils.isEmpty(getIntent().getStringExtra("BOOKID"))) {
            initGetTest(getIntent().getStringExtra("BOOKID"));
        }
        lvRank.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (null != testRankList && testRankList.size() > 0) {
                    if (StringUtils.isEmpty(testRankList.get(position).getUser().getHeadPortrait())) {
                        ivHead.setImageResource(R.mipmap.mf_logo);
                    } else {
                        CircleCrop circleCrop = new CircleCrop();
                        RequestOptions options = RequestOptions.bitmapTransform(circleCrop);
                        Glide.with(TestActivity.this).asBitmap().load(testRankList.get(position).getUser().getHeadPortrait()).listener(new MyRequestListener(ivHead, TestActivity.this, DeviceUtils.dip2px(TestActivity.this, 67), DeviceUtils.dip2px(TestActivity.this, 67))).apply(options).into(new TransformationUtils(ivHead, TestActivity.this, DeviceUtils.dip2px(TestActivity.this, 67), DeviceUtils.dip2px(TestActivity.this, 67)));
                    }
                    tvName.setText(testRankList.get(position).getUser().getName());
                }
            }
        });
        IntentFilter mFilter = new IntentFilter();
        mFilter.addAction("REFRESHPAGE");
        registerReceiver(mReceiver, mFilter);
    }

    private BroadcastReceiver mReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals("REFRESHPAGE")){
                if (!StringUtils.isEmpty(intent.getStringExtra("BOOKID"))) {
                    initGetTest(intent.getStringExtra("BOOKID"));
                }
            }
        }
    };

    @Override
    protected void onResume() {
        super.onResume();
        if (null != MoreFunApplication.loginBean && null != MoreFunApplication.loginBean.getResult() && null != MoreFunApplication.loginBean.getResult().getOrgan()) {
            if (!StringUtils.isEmpty(testId)) {
                initGetTestRank(testId, MoreFunApplication.loginBean.getResult().getOrgan().getId());
            }
        }
    }

    private void initGetTest(String bookId) {
        if (null != dialog && !dialog.isShow()) {
            dialog.show();
        }
        RequestParams params = new RequestParams(Configuration.HOST + Configuration.GETTEST);
        RequestTestBean requestTestBean = new RequestTestBean();
        RequestTestBean.MfTestBean mfTestBean = new RequestTestBean.MfTestBean();
        RequestTestBean.MfTestBean.BookBean bookBean = new RequestTestBean.MfTestBean.BookBean();
        bookBean.setId(bookId);
        mfTestBean.setBook(bookBean);
        requestTestBean.setMfTest(mfTestBean);
        params.setBodyContent(JSON.toJSONString(requestTestBean));
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                if (null != MoreFunApplication.mTestList && MoreFunApplication.mTestList.size() > 0) {
                    MoreFunApplication.mTestList.clear();
                }
                if (null != dialog && dialog.isShow()) {
                    dialog.cancel();
                }
                if (!StringUtils.isEmpty(result)) {
                    ResultBean resultBean = JSON.parseObject(result, ResultBean.class);
                    if (resultBean.getErrorCode() == 0) {
                        if (!StringUtils.isEmpty(resultBean.getResult())) {
                            List<TestBean> testList = JSON.parseArray(resultBean.getResult(), TestBean.class);
                            if (null != MoreFunApplication.mTestList) {
                                MoreFunApplication.mTestList.addAll(testList);
                            }
                            if (null != testList && testList.size() > 0) {
                                if (null != MoreFunApplication.loginBean && null != MoreFunApplication.loginBean.getResult() && null != MoreFunApplication.loginBean.getResult().getOrgan()) {
                                    if (null != testList.get(0).getMfTest()) {
                                        testId = testList.get(0).getMfTest().getId();
                                        initGetTestRank(testId, MoreFunApplication.loginBean.getResult().getOrgan().getId());
                                    }
                                }
                            }
                        } else {
                            ToastUtils.show(getApplicationContext(), "该绘本还没有测试题！", 100);
                        }
                    } else {
                        ToastUtils.show(getApplicationContext(), resultBean.getMessage(), 100);
                    }
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                if (null != dialog && dialog.isShow()) {
                    dialog.cancel();
                }
                mHandler.sendEmptyMessage(101);
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

    //获取排行榜
    private void initGetTestRank(String testId, String orginId) {
        RequestParams params = new RequestParams(Configuration.HOST + Configuration.TESTRANK);
        RequestTestRankBean requestTestRankBean = new RequestTestRankBean();
        RequestTestRankBean.TestBean testBean = new RequestTestRankBean.TestBean();
        testBean.setId(testId);
        RequestTestRankBean.OrganBean organBean = new RequestTestRankBean.OrganBean();
        organBean.setId(orginId);
        requestTestRankBean.setTest(testBean);
        requestTestRankBean.setOrgan(organBean);
        params.setBodyContent(JSON.toJSONString(requestTestRankBean));
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                testRankList.clear();
                if (!StringUtils.isEmpty(result)) {
                    ResultBean resultBean = JSON.parseObject(result, ResultBean.class);
                    if (resultBean.getErrorCode() == 0) {
                        if (!StringUtils.isEmpty(resultBean.getResult())) {
                            List<TestRankBean> testRankBeanList = JSON.parseArray(resultBean.getResult(), TestRankBean.class);
                            testRankList.addAll(testRankBeanList);
                            if (null != testRankList && testRankList.size() > 0) {
                                //设置图片圆角角度
                                CircleCrop circleCrop = new CircleCrop();
                                RequestOptions options = RequestOptions.bitmapTransform(circleCrop);
                                Glide.with(TestActivity.this).asBitmap().load(testRankList.get(0).getUser().getHeadPortrait()).listener(new MyRequestListener(ivHead, TestActivity.this, DeviceUtils.dip2px(TestActivity.this, 67), DeviceUtils.dip2px(TestActivity.this, 67))).apply(options).into(new TransformationUtils(ivHead, TestActivity.this, DeviceUtils.dip2px(TestActivity.this, 67), DeviceUtils.dip2px(TestActivity.this, 67)));
                                tvName.setText(testRankList.get(0).getUser().getName());
                            }
                        } else {
                            ToastUtils.show(getApplicationContext(), "数据为空", 100);
                        }
                    } else {
                        ToastUtils.show(getApplicationContext(), resultBean.getMessage(), 100);
                    }
                }
                adapter.notifyDataSetChanged();
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                mHandler.sendEmptyMessage(101);
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }


    private class mRequestListener implements RequestListener {
        private ImageView holder;

        public mRequestListener(ImageView holder) {
            this.holder = holder;
        }

        @Override
        public boolean onLoadFailed(@Nullable GlideException e, Object model, Target target, boolean isFirstResource) {
            Log.d(TAG, "onException: " + e.toString() + "  model:" + model + " isFirstResource: " + isFirstResource);
            Message msg = new Message();
            msg.what = 0;
            msg.obj = holder;
            mHandler.sendMessage(msg);
            return false;
        }

        @Override
        public boolean onResourceReady(Object resource, Object model, Target target, DataSource dataSource, boolean isFirstResource) {
            Log.e(TAG, "model:" + model + " isFirstResource: " + isFirstResource);
            return false;
        }
    }

    ;

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 0:
                    Glide.with(TestActivity.this).asBitmap().load(R.mipmap.ic_launcher).into(new TransformationTestUtils((ImageView) msg.obj, TestActivity.this));
                    break;
                case 101:
                    NetErrorPop errorPop = new NetErrorPop(TestActivity.this);
                    errorPop.showPop("");
                    break;
            }
        }
    };

    @Override
    protected void initData() {

    }

    @OnClick({R.id.iv_back, R.id.tv_recharge})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.tv_recharge://重新挑战
                if (null != MoreFunApplication.mTestList && MoreFunApplication.mTestList.size() > 0 && !StringUtils.isEmpty(getIntent().getStringExtra("BOOKID"))) {
                    Intent mIntent = new Intent(TestActivity.this, DoTestActivity.class);
                    mIntent.putExtra("BOOKID", getIntent().getStringExtra("BOOKID"));
                    startActivity(mIntent);
                }
                break;
        }
    }
}
